<template>
  <div class="flex flex-col">
    <div class="flex justify-between items-center">
      <div class="title">{{ t("formula_detail.material_list") }}</div>
      <div class="flex items-center">
        <span class="text-[--autata-font-gray-color]">{{
          t("formula_detail.max_material_warning")
        }}</span>
        <el-button type="primary" @click="addMat">{{
          t("formula_detail.add_material")
        }}</el-button>
      </div>
    </div>
    <div class="h-[calc(100vh_-_255px)] material-table">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #index_default="{ row }">
          <vxe-input
            v-model="row.index"
            class="mat-num-input"
            :placeholder="t('formula_detail.positive_number')"
            type="number"
            min="0"
            clearable
          />
        </template>
      </AuTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import { getCurrentInstance, reactive, ref, watch } from "vue";
import { AuTable } from "@/components/AuTable";
import { getMaterialList } from "@/api/cabinet/material";
import { cloneDeep } from "lodash-unified";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const props = defineProps<{
  matIds: (string | number)[];
  materialList: any[];
}>();
const emits = defineEmits(["pageBefore", "matIdsChange"]);

const { proxy } = getCurrentInstance();
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showIndex: false,
  showExportBtn: false,
  columns: [
    {
      field: "index",
      title: "formula_detail.material_order",
      slots: { default: "index_default" }
    },
    { field: "name", title: "formula_detail.material_name" },
    {
      field: "type_name",
      title: "formula_detail.material_type"
    }
  ],
  actions: [ACTION_TYPE.DELETE],
  topTools: [],
  operateTools: [],
  dataSource: [],
  vxeTableConfig: {
    pagerConfig: {
      enabled: false
    }
  }
});
const initialized = ref(false); // 初始化状态标识

const addMat = () => {
  emits("pageBefore");
  proxy.$router.push({
    name: "CabinetDetailMaterial",
    query: {
      ...proxy.$route.query,
      matIds: JSON.stringify(gridOption.dataSource.map(v => v.material_id))
    }
  });
};

function getMaterialInit(data: any[]) {
  gridOption.dataSource = data.map((v, i) => {
    return {
      ...v,
      index: v.index || 1
    };
  });
}

async function getMaterialData(ids: (string | number)[]) {
  try {
    // 获取物料列表
    const res = await getMaterialList({ size: 0, hiddenDeviceType: true });

    if (!res || !res.data || res.data.length === 0) {
      console.warn("Response data is empty or undefined");
      return;
    }

    // 构建现有 dataSource 的 material_id -> index 映射
    const existingIndexMap = new Map(
      gridOption.dataSource.map(item => [item.material_id, item.index])
    );

    // 更新 dataSource
    gridOption.dataSource = res.data
      .filter(item => ids.includes(item.material_id))
      .map(item => {
        // 如果已有 index，则保留；否则默认为 1
        const index = existingIndexMap.get(item.material_id) || 1;
        return {
          ...item,
          index
        };
      });

    // 触发事件
    emits("matIdsChange");
  } catch (error) {
    console.error("Error fetching material data:", error);
  }
}

type ActionType = {
  key: ACTION_TYPE | string;
  row: any;
};
const actionClick = ({ key, row }: ActionType) => {
  switch (key) {
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(t("formula_detail.delete_confirm"))
        .then(() => {
          const clone = cloneDeep(gridOption.dataSource);
          clone.splice(
            clone.findIndex(v => v.material_id === row.material_id),
            1
          );
          gridOption.dataSource = clone;
          emits("matIdsChange");
        });
  }
};

defineExpose({
  getMatIds: () => gridOption.dataSource.map(v => v.material_id),
  getMatList: () =>
    gridOption.dataSource.map((v, i) => {
      const data = {};
      for (const ele in v) {
        data[ele] = v[ele] == "/" ? null : v[ele];
      }
      return {
        ...data
      };
    })
});

watch(
  () => props.matIds,
  val => {
    if (val?.length) {
      console.log("使用ID列表初始化", val);
      getMaterialData(val);
      initialized.value = true;
    }
  },
  { immediate: true }
);

watch(
  () => props.materialList,
  val => {
    if (val?.length) {
      console.log("使用对象列表初始化", val);
      getMaterialInit(val);
    }
  },
  { immediate: true, deep: true }
);
</script>

<style scoped>
.title {
  position: relative;
  padding-left: 12px;
  color: var(--autata-font-color);

  &::before {
    position: absolute;
    top: 4px;
    left: 0;
    width: 2px;
    height: 14px;
    content: "";
    background-color: var(--el-color-primary);
  }
}

.material-table > div {
  padding: 0;
}

.mat-num-input {
  :deep(.vxe-input--control-icon) {
    display: none;
  }
}
</style>
